package service

import (
	"duoke/internal/dao"
	"duoke/internal/model/entity"
	"duoke/model"
	"duoke/tables"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/frame/g"
)

// Withdrawal 提现
var Withdrawal = new(withdrawalService)

type withdrawalService struct{}

func (s *withdrawalService) Save(c *gin.Context, req *entity.WithdrawalLog) error {
	begin, err := g.DB().Begin(c)
	if err != nil {
		return err
	}
	_, err = begin.Model("withdrawal_log").Insert(req)
	if err != nil {
		begin.Rollback()
		return err
	}
	if req.State == "WAIT_USER_CONFIRM" || req.State == "TRANSFERING" {
		_, err = begin.Model("withdrawal").Where("id=?", req.WithdrawalId).Update(g.Map{
			"state":         4,
			"freeze_amount": 0,
		})
		if err != nil {
			begin.Rollback()
			return err
		}
	}
	if err = begin.Commit(); err != nil {
		begin.Rollback()
		return err
	}
	return nil
}
func (s *withdrawalService) Info(c *gin.Context, req *model.SearchWithdrawal) (*tables.Withdrawal, error) {
	var m tables.Withdrawal
	where := g.Map{}
	if req.Id != 0 {
		where["id=?"] = req.Id
	}
	err := dao.Withdrawal.Ctx(c).Where(where).Scan(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}
func (s *withdrawalService) List(c *gin.Context, req *model.SearchWithdrawal) (*model.RspList, error) {
	user, err := Request.User(c)
	if err != nil {
		return nil, err
	}
	var count int
	var withdrawal []tables.Withdrawal
	g := g.Map{}
	g["user_id=?"] = user.Id
	if req.State != 0 {
		g["state=?"] = req.State
	}
	err = dao.Withdrawal.Ctx(c).Where(g).
		Page(req.PageNo, req.PageSize).OrderDesc("id").ScanAndCount(&withdrawal, &count, false)
	if err != nil {
		return nil, errors.New("获取提现列表失败")
	}
	return &model.RspList{
		Total: int64(count),
		List:  &withdrawal,
	}, nil
}
func (s *withdrawalService) WithdrawalLogInfo(c *gin.Context, req *model.SearchWithdrawal) (*tables.WithdrawalLog, error) {
	user, err := Request.User(c)
	where := g.Map{}
	if err == nil && user.Id != 0 {
		where["user_id=?"] = user.Id
	}
	var m tables.WithdrawalLog
	if req.WithdrawalId != 0 {
		where["withdrawal_id=?"] = req.WithdrawalId
	}
	if req.OutBillNo != "" {
		where["out_bill_no=?"] = req.OutBillNo
	}
	if err = dao.WithdrawalLog.Ctx(c).Where(where).Scan(&m); err != nil {
		return nil, nil
	}
	return &m, nil
}
func (s *withdrawalService) Update(c *gin.Context, req *model.SearchWithdrawal) error {
	where := g.Map{}
	if req.State != 0 {
		where["state=?"] = req.State
	}
	result, err := dao.Withdrawal.Ctx(c).Where("id=?", req.WithdrawalId).Update(where)
	if err != nil {
		return err
	}
	affected, err := result.RowsAffected()
	if err != nil || affected == 0 {
		return errors.New("更新提现失败")
	}
	return nil
}
